const app = getApp()
//数据库
const db = wx.cloud.database()
const _ = db.command
const $ = db.command.aggregate
//查询所有记录
async function quearyAllNote() {
  return loadMore(0, 20)
  // wx.cloud.callFunction({
  //   name: 'note',
  //   data: {
  //     action: 'quearyAllNote',
  //   }
  // });
}
//查询所有记录 本地
async function quearyAllNoteByLocal() {
  return await new Promise((success, fail) => {
    let list = wx.getStorageSync('notes') || []
    success(list)
  })
}
//添加记录
async function addNote(params, isCache) {
  if (app.isNetworkAvailable()) {
    params.updateTime = Date.now();
    params.setTopTime = 0
    return await db.collection('notes').add({
      data: params
    })
    // wx.cloud.callFunction({
    //   name: 'note',
    //   data: {
    //     action: 'addNote',
    //     data: params
    //   }
    // });
  } else if (isCache) {
    return addNoteLocal(params)
  } else {
    return await new Promise((success, fail) => {
      fail()
    })
  }

}
//添加 本地数据
async function addNoteLocal(params) {
  return quearyAllNoteByLocal()
    .then(list => new Promise((success, fail) => {
      params.updateTime = Date.now();
      //添加
      list.unshift(params)
      //保存
      wx.setStorageSync('notes', list)
      success({
        local: true
      })
    }))
}
//删除
async function deleteNote(parmas) {
  if (app.isNetworkAvailable()) {
    const id = parmas._id
    delete parmas._id
    delete parmas.index
    parmas.remove = true
    return await db.collection('notes').doc(id).remove()
    // wx.cloud.callFunction({
    //   name: 'note',
    //   data: {
    //     action: 'deleteNote',
    //     _id: id
    //   }
    // });
  } else {
    return deleteNoteLocal(parmas.index)
  }

}
//删除 本地信息
async function deleteNoteLocal(index) {
  return quearyAllNoteByLocal()
    .then(list => new Promise((success, fail) => {
      //删除
      list.splice(index, 1)
      //保存
      wx.setStorageSync('notes', list)
      success()
    }))
}
//修改
async function updateNote(params) {

  if (app.isNetworkAvailable()) {
    const id = params._id
    delete params._id
    delete params.index
    return await db.collection('notes').doc(id).update({
      data: params
    })
    // wx.cloud.callFunction({
    //   name: 'note',
    //   data: {
    //     action: 'updateNote',
    //     _id: id,
    //     data: params
    //   }
    // });
  } else {
    return updateNoteLocal(params)
  }

}
async function updateNoteLocal(params) {
  return quearyAllNoteByLocal().then(list => new Promise((success, fail) => {
    const index = params.index
    delete params.index
    //删除
    list.splice(index, 1)
    //添加
    list.unshift(params)
    //保存
    wx.setStorageSync('notes', list)
    //返回
    success()
  }))
}

//置顶
async function setItemTop(params) {

  return await db.collection("notes").doc(params._id).update({
    data: {
      isTop: _.set(params.isTop),
      setTopTime: _.set(params.setTopTime)
    }
  })
}

//分页
async function loadMore(skip, limit) {
  return await db.collection('notes').aggregate()
    .project({
      content: 1,
      isTop: 1,
      title: 1,
      time: 1,
      setTopTime: 1,
      updateTime: 1,
      newTime: $.add(['$updateTime', '$setTopTime'])
    })
    .sort({
      newTime: -1,
    })
    .skip(skip)
    .limit(limit)
    .end()
}
//获取总数
async function getTotalCount() {
  return await db.collection("notes")
    .field({
      _openid: false
    })
    .count()
}

async function searchByKey(key) {
  return await db.collection("notes").aggregate()
  .match({       
    title:db.RegExp({
      regexp:key,
      options:'i'
    })
  })
  .project({
    content: 1,
    isTop: 1,
    title: 1,
    time: 1,
    setTopTime: 1,
    updateTime: 1,
    newTime: $.add(['$updateTime', '$setTopTime'])
  })
  .sort({
    newTime: -1,
  }).end()
  
}

module.exports = {
  quearyAllNote: quearyAllNote,
  addNote: addNote,
  deleteNote: deleteNote,
  updateNote: updateNote,
  quearyAllNoteByLocal: quearyAllNoteByLocal,
  setItemTop: setItemTop,
  loadMore: loadMore,
  getTotalCount: getTotalCount,
  searchByKey:searchByKey
}